package com.tenton.servlet;

import com.tenton.pojo.User;
import com.tenton.service.Impl.UserServiceImpl;
import com.tenton.service.UserService;
import com.tenton.utils.ConstantClassUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Date: 2021/1/18
 * @Author: Tenton
 * @Description:
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式，防止乱码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        UserService userService = new UserServiceImpl();
        //获取用户名
        String userName = request.getParameter("userName");
        //获取登录密码
        String password = request.getParameter("password");
        //获取用户类型
        String role = request.getParameter("userType");
        Boolean flag = userService.getAdmin(userName, password, role);
        //管理员登录或者普通用户登录
        if (flag){
            if (ConstantClassUtils.ADMINTYPE.equals(role)){
                //重定向跳转到管理员主界面
                response.sendRedirect("/adminMain.jsp");
            }else {
                //存一个session，用来存登录用户的id，用户登录后的一些操作
                HttpSession session = request.getSession();
                User user = userService.getUser(userName, password);
                //将用户Id存入session，用户购物车与订单的增添
                session.setAttribute("userId",user.getId());
                //重定向跳转到普通用户主界面
                response.sendRedirect("/userMain.jsp");
            }
        }else {
            //登录失败，用户名或密码错误，返回登录界面
            response.getWriter().write("用户名或密码错误，2秒后自动跳转到登陆界面");
            response.setHeader("Refresh","3;URL=login.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
